package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.application.factory.SyncFactory;
import com.wlyuan.open.scanner.assembler.ScannerGoodsAssembler;
import com.wlyuan.open.scanner.config.GroupProperties;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.dao.entity.GoodsDO;
import com.wlyuan.open.scanner.dao.mapper.CustomerMapper;
import com.wlyuan.open.scanner.dao.mapper.GoodsMapper;
import com.wlyuan.open.scanner.domain.goods.Goods;
import com.wlyuan.open.scanner.domain.goods.GoodsConvert;
import com.wlyuan.open.scanner.repository.GoodsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GoodsRepositoryImpl implements GoodsRepository {
    private final GoodsMapper goodsMapper;
    private final CustomerMapper customerMapper;
    private final SyncFactory syncFactory;
    private final GroupProperties groupProperties;

    @Override
    public void sync() {
        logger.info("物品创建租户 > 0 ,物品客户id > 0");
        int count = goodsMapper.count();
        logger.info("物品老数据数据量，size：{}", count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        for (int i = 1; i <= pages; i++) {
            logger.info("开始同步物品：第{}页，共{}页", i, pages);
            var list = goodsMapper.getGoodsIds(i, Constants.PAGE_SIZE);
            list.forEach(id -> {
                try {
                    var data = goodsMapper.getById(id);
                    process(data);
                    syncFactory.sync(ScannerGoodsAssembler.assemble(GoodsConvert.convert(data)));
                } catch (Exception e) {
                    logger.error("物品同步异常：{}，{}", id, e);
                }
            });
        }
        logger.info("物品同步完成......");
    }

    @Override
    public List<Goods> list() {
        return Collections.emptyList();
    }

    @Override
    public Goods getById(Long goodsId) {
        return Optional.ofNullable(goodsId).map(id -> {
            var goods = goodsMapper.getById(id);
            process(goods);
            return GoodsConvert.convert(goods);
        }).orElse(null);
    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return goodsMapper.getByTime(startTime, endTime);
    }

    @Override
    public List<Long> getByTenantIdTime(Long tenantId, String startTime, String endTime) {
        return goodsMapper.getByTenantIdTime(tenantId, startTime, endTime);
    }

    @Override
    public void getByTenantId(Long tenantId) {
        logger.info("物品创建租户 > 0 ,物品客户id > 0");
        int count = goodsMapper.countByTenantId(tenantId);
        logger.info("租户{}物品老数据数据量，size：{}", tenantId, count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        for (int i = 1; i <= pages; i++) {
            logger.info("开始同步租户{}物品：第{}页，共{}页", tenantId, i, pages);
            var list = goodsMapper.getGoodsIdsByTenantId(i, Constants.PAGE_SIZE, tenantId);
            list.forEach(id -> {
                try {
                    var data = goodsMapper.getById(id);
                    process(data);
                    syncFactory.sync(ScannerGoodsAssembler.assemble(GoodsConvert.convert(data)));
                } catch (Exception e) {
                    logger.error("物品同步异常：{}，{}", id, e);
                }
            });
        }
        logger.info("租户{}物品同步完成......", tenantId);
    }

    @Override
    public void process(GoodsDO goods) {
        Optional.ofNullable(goods).ifPresent(data -> {
            if (StringUtils.isBlank(data.getUnit())) {
                data.setUnit("其他");
            }
            if (StringUtils.isBlank(data.getType())) {
                data.setType("其他");
            }
            if (data.getGoodsPrice() != null && data.getGoodsPrice().compareTo(Constants.MAX_VALUE.doubleValue()) > 0) {
                data.setGoodsPrice(Constants.MAX_VALUE.doubleValue());
            }
            if (groupProperties.groupTenantList().contains(data.getGoodsCreatorcompanyid())) {
                data.setGoodsCreator(0L);
                data.setGoodsUpdater(0L);
                //老系统客户名称与新系统试用数据名称不一致 如：脱普日用化学品（中国）有限公司 --> 脱普日用化学品
                var customer = customerMapper.getById(data.getGoodsCustomerid());
                if (!Optional.ofNullable(customer).isPresent()) {
                    data.setCustomerName(Constants.GROUP_MAP.get(data.getGoodsCreatorcompanyid()));
                } else if (customer.getCustomerOwnercompany().equals(customer.getCustomerCompanyid()) || customer.getCustomerUnderline() == 0) {
                    data.setCustomerName(Constants.GROUP_MAP.get(data.getGoodsCreatorcompanyid()));
                }
            }
        });
    }
}